﻿using Crawler.Core.CrawlerHandler.UrlChecker;
using Crawler.Core.EventBus;
using Crawler.IRepositories;
using Crawler.IRepositories.SystemDefault;
using Crawler.Model.SystemDefault;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Linq;
using Crawler.Common;
using Crawler.Core.CrawlerHandler.Analyzer;
using Crawler.Core.CrawlerHandler.Collector;

namespace Crawler.Core
{
    public class CrawlerManager
    {
        private readonly IRepository<CollectInfoConfigModel> collectInfoConfigRepository;
        private readonly IEventBus eventBus;
        private readonly IRepository<TerminalConfigModel> terminalConfigRepository;

        public CrawlerManager(
             IRepository<CollectInfoConfigModel> collectInfoConfigRepository
             , IEventBus eventBus
            , IRepository<TerminalConfigModel> terminalConfigRepository
            )
        {
            this.collectInfoConfigRepository = collectInfoConfigRepository;
            this.eventBus = eventBus;
            this.terminalConfigRepository = terminalConfigRepository;
        }

        public void Start()
        {
            Console.WriteLine("Setup!");

            //订阅事件
            eventBus.Subscribe<UrlCheckerHandler, UrlCheckerEventEntity>();
            eventBus.Subscribe<CollectorHandler, CollectorEventEntity>();
            eventBus.Subscribe<AnalyzerHandler, AnalyzerEventEntity>();

            while (true)
            {
                Thread.Sleep(200);
                try
                {
                    //取还没有处理的任务
                    var collectInfos = collectInfoConfigRepository.Find(c=>c.CollectorStatus == CollectorStatus.Available&&c.WorkStatus== WorkStatus.Pending);
                    if (collectInfos.Count() > 0)
                    {
                        //获取终端配置
                        var terminalConfig = terminalConfigRepository.Find(Constant.AppSetting.TerminalId);
                        if (terminalConfig == null)
                        {
                            Console.WriteLine($"终端不存在:{Constant.AppSetting.TerminalId}");
                            continue;
                        }

                        foreach (var configModel in collectInfos)
                        {
                            /*
                             * 将任务插入队列，并且 更新任务状态
                             * 
                             */
                            Console.WriteLine("***new task***:" + configModel.Name);
                            //这个最新更新时间，将来通过web来控制时，在设置任务开启前就应该重置这个时间，避免导致其它任务判断时间错误执行处理
                            configModel.LatestCollectTime = DateTime.Now;
                            configModel.WorkStatus = WorkStatus.Running;//更新为正在运作
                            collectInfoConfigRepository.Update(configModel);
                            Thread.Sleep(1000);//暂停1s，保证时间差
                            eventBus.Publish(new UrlCheckerEventEntity
                            {
                                collectorUrlModel = new CollectorUrlModel
                                {
                                    AddTime = DateTime.Now,
                                    CollectorConfigID = configModel.ID,
                                    CollectStatus = CollectStatus.Default,
                                    Depth = 0,
                                    ErrorTimes = 0,
                                    Url = configModel.StartUrl

                                }
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

            }
        }
    }
}
